<template>
  <div class="product-message product-wrap medias font-size-14 font-weight-400 line-height-140 gap-col-16">
    <div class="outer-container" ref="outerElement">
      <div class="scroll-container gap-row-8" @touchstart.stop @touchmove.stop ref="scrollElement">
        <div v-for="(media, index) in mediaList" class="media" :key="media.id" ref="itemRefs">
          <div @click="() => onMediaClicked(index)">
            <EncryptImage
              :src="media.need_buy ? media.img_path_blur_mini : media.img_path_mini"
              :width="isSinggleMedia ? 226 : 109"
              :height="165"
              :border-radius="10"
              object-fit="cover"
            ></EncryptImage>
            <div v-if="getTopRightIcon(media)" class="top-right">
              <Icon :name="getTopRightIcon(media)" size="12"></Icon>
            </div>
            <div v-if="isVideo(media)" class="video-time font-size-10 font-weight-400 line-height-120">
              {{ getTransDuration(media.video_time) }}
            </div>
            <div v-if="showLockMask(media)" class="mask">
              <Icon name="lock" size="54"></Icon>
            </div>
          </div>
        </div>
      </div>
      <SwipeArrow
        :show-left="showLeft"
        :show-right="showRight"
        :to-left="moveToLeft"
        :to-right="moveToRight"
        :top="90"
      ></SwipeArrow>
    </div>
    <button class="buy-btn font-size-14 font-weight-500 primary-gradient" @click="onBtnClick">
      <div v-if="forBuy">{{ `$${item.price}` }} {{ $t('common.buyProduct') }}</div>
      <div v-else>{{ $t('common.watchUnlockContent') }}</div>
    </button>
    <button v-if="forBuy" class="buy-btn font-size-14 font-weight-500" @click="toCreatorPage">
      {{ $t('common.watchCreatorPage') }}
    </button>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useChatStore } from '@/store/chat'
import { useFeedStore } from '@/store/feed'
import { isMultiPhoto, isPhoto, isVideo, showLockMask } from '@/utils/feed-status'
import { repairZero } from '@/utils/string-helper'
import SwipeArrow from '@/components/common/SwipeArrow.vue'
import EncryptImage from '@/components/multimedia/EncryptImage.vue'
import { useHorizontalScroll } from '@/compositions/sensor/horizontal-scroll'

const feedStore = useFeedStore()
const { getFeedList } = feedStore
const mediaList = ref([])
onMounted(async () => {
  const ids = props.item.media_list.map((e) => e.id)
  mediaList.value = await getFeedList(ids)
})

const props = defineProps({
  text: { type: String, required: true },
  item: { type: Object, required: true },
  self: { type: Boolean, default: false },
})
const emits = defineEmits(['click:media', 'click:buy', 'click:creator'])

const outerElement = ref(null)
const scrollElement = ref(null)
const itemRefs = ref([])

const { showLeft, showRight, moveToLeft, moveToRight } = useHorizontalScroll(outerElement, scrollElement, itemRefs)

const forBuy = computed(() => !mediaList.value.every((e) => !e.need_buy))
const isSinggleMedia = computed(() => mediaList.value.length === 1)

function getTopRightIcon(media) {
  if (isVideo(media)) return 'video'
  if (isMultiPhoto(media)) return 'multiPhoto'
  if (isPhoto(media)) return 'singlePhoto'
  return ''
}

function onBtnClick() {
  if (forBuy.value) {
    emits('click:buy', props.item)
  } else {
    if (!props.item.media_list[0]) throw new Error('不對吧，怎麼可能購買了還沒有媒體可以看😡')
    // 已經購買了，按下去就直接開啟第一個媒體
    emits('click:media', { item: props.item, index: 0 })
  }
}

function onMediaClicked(index) {
  emits('click:media', { item: props.item, index })
}

function getTransDuration(time) {
  if (!time) return '00:00'
  return `${repairZero(parseInt(time / 60))}:${repairZero(time % 60)}`
}

const { currentChatCreator } = storeToRefs(useChatStore())

function toCreatorPage() {
  if (!currentChatCreator.value) {
    console.warn('Current chat creator is not exist, how to go to creator page?🧐')
    return
  }

  emits('click:creator', { aff: currentChatCreator.value.id, username: currentChatCreator.value.username })
}
</script>
<style lang="scss" scoped>
.product-message {
  width: fit-content;
  padding: 0.5rem 1rem;
  background: rgb(var(--v-theme-primary-gray));
  border-radius: 1rem 1rem 1rem 1rem;

  &.product-wrap {
    width: 15.125rem;
    padding: 1rem 0.5rem;
    position: relative;
  }

  &.self {
    background: rgb(var(--v-theme-primary));
  }

  &.medias {
    max-width: 100%;

    .outer-container {
      position: relative;
      width: 100%;
    }

    .scroll-container {
      display: flex;
      width: 100%;
      max-width: 100%;
      overflow-x: auto;

      min-height: 10.625rem;

      &::-webkit-scrollbar {
        height: 0.25rem;
        display: block;
      }
      &::-webkit-scrollbar-track {
        background: var(--color-primary-divider, rgba(215, 215, 215, 0.4));
      }
      &::-webkit-scrollbar-thumb {
        background: var(--color-primary-divider, rgba(215, 215, 215, 0.8));
        border-radius: 0.09375rem;
        border: 0.35rem solid transparent;
      }
      .media {
        border-radius: 0.625rem;
        flex-shrink: 0;
        position: relative;
        .mask {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          border-radius: 0.625rem;
          background: linear-gradient(180deg, rgba(249, 94, 14, 0.2) 0%, rgba(231, 23, 179, 0.2) 100%);

          display: flex;
          justify-content: center;
          align-items: center;
        }
        .top-right {
          width: 1rem;
          height: 1rem;
          border-radius: 0.5rem;
          background: rgba(var(--v-theme-background), 0.4);
          position: absolute;
          top: 0.3125rem;
          right: 0.3125rem;

          display: flex;
          justify-content: center;
          align-items: center;
        }
        .video-time {
          position: absolute;
          bottom: 0.3125rem;
          left: 0.3125rem;
          padding: 0.125rem 0.25rem;
        }
      }
    }
  }

  .buy-btn {
    width: 100%;
    padding: 0.5rem 0.75rem;
    border-radius: 1.25rem;
  }
}
</style>
